<template>
  <!-- 工时维护店端-经销商端页面 -->
  <div>
    <!--条件筛选-->
    <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="110" :formType="type" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <!--操作 -->
    <button-area :style="{ paddingLeft: '80px' }"></button-area>
    <!-- 列筛选-->
    <FilterTable
      ref="table"
      columnsRef="repair-labourHour-info"
      :isSelectColumn="false"
      :columns="columns"
      :dataSource="dataSource"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onSyncTableData="syncTableFun"
    >
      <!--列操作-->
      <template slot="controls">
        <el-button v-show="!(this.type === 'show')" :disabled="addModelBtnDisable" size="small" type="primary" icon="el-icon-plus" @click="addRowClick">添加车型</el-button>
      </template>
    </FilterTable>

    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <AjaxButton v-show="!(this.type === 'show')" type="primary" :click="saveDialog">保 存</AjaxButton>
      <el-button @click="closeDialog">关 闭</el-button>
      <BaseDialog :visible.sync="showChooseModel" title="车型选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <chooseModel @close="closeChooseModelDialog" />
      </BaseDialog>
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import dictCode from '@/utils/dictCode';
import { getSeries } from '@/api/repair/estimateExtension';
import { getLabour, saveLabour } from '@/api/repair/repairBusiness/labourHour/index.js';
import FormPanel from '../../../../components/FormPanel/FormPanel.vue';
import chooseModel from '@/pages/repair/repairBusiness/labourHour/chooseModel';
import { banWord } from '@/utils/validate.js';

// 延保订单查询
export default {
  name: 'repair-labourHour-info',
  props: {
    row: {
      type: Object,
      default: {}
    },
    type: {
      // edit show add三种状态
      type: String,
      default: 'add'
    }
  },
  components: { FormPanel, chooseModel },
  mixins: [dictionary],
  data() {
    return {
      showChooseModel: false,
      columns: this.createTableColumns(),
      dataSource: [],
      handleType: '',
      formData: {},
      tableData: [],
      selectFlag: false,
      formList: this.createFormList(),
      estimate: false,
      addModelBtnDisable: false
    };
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    if (this.type === 'add') {
    } else {
      this.formList.forEach(x => {
        x.initialValue = this.row[x.fieldName];
        if (x.fieldName === 'labourCode') {
          x.disabled = true; // 不允许编辑
        }
      });

      // 全部车型时，禁用添加车型按钮
      if (this.row.isAllModel == 10041001) {
        this.addModelBtnDisable = true;
        this.formList.find(x => x.fieldName == 'stdLabourHour').disabled = false;
      } else {
        this.formList.find(x => x.fieldName == 'stdLabourHour').initialValue = undefined;
        this.getLabour(); //针对全部车型，不发起请求
      }
      if (this.type === 'show') {
        this.formList.forEach(x => {
          x.disabled = true;
          x.rules = [];
        });
        this.columns.forEach(x => {
          x.defaultEditable = false;
          x.editable = false;
        });
        this.addModelBtnDisable = true;
      }
    }
  },
  methods: {
    async getLabour() {
      let res = await getLabour({ labourCode: this.row.labourCode, dataSources: this.row.dataSources });
      if (res.resultCode === 200) {
        this.dataSource = res.data;
      }
    },
    createFormList() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '工时信息',
          style: {}
        },
        {
          type: 'INPUT',
          label: '工时代码',
          fieldName: 'labourCode',
          rules: [
            { required: true, message: '请输入...', trigger: 'change' },
            { required: true, validator: banWord, trigger: 'change' },
            { max: 30, message: '工时代码不能超过30个字符', trigger: 'change' }
          ]
        },
        {
          type: 'INPUT',
          label: '工时名称',
          fieldName: 'labourName',
          rules: [{ required: true, message: '请输入...', trigger: 'change' }],
          maxlength: 100
        },
        {
          type: 'SELECT',
          label: '状态',
          fieldName: 'itemStatus',
          itemList: this.createDictList('1003'),
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '数据来源',
          fieldName: 'dataSources',
          disabled: true,
          initialValue: 10451001,
          placeholder: '请选择...',
          itemList: this.createDictList('1045')
        },
        {
          type: 'CHECKBOX',
          label: '设置全部车型',
          fieldName: 'isAllModel',
          options: {
            trueValue: 10041001,
            falseValue: 10041002
          },
          initialValue: 10041002,
          change: val => {
            if (val == 10041001) {
              // 全部车型
              this.formList.find(x => x.fieldName === 'stdLabourHour').disabled = false;
              this.formList.find(x => x.fieldName === 'stdLabourHour').rules = [{ required: true, message: '请输入...', trigger: 'blur' }];
              this.dataSource = [];
              this.addModelBtnDisable = true;
            } else {
              this.formList.find(x => x.fieldName === 'stdLabourHour').disabled = true;
              this.formList.find(x => x.fieldName === 'stdLabourHour').initialValue = undefined;
              this.formList.find(x => x.fieldName === 'stdLabourHour').rules = [];
              this.addModelBtnDisable = false;
            }
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '所有车型工时',
          fieldName: 'stdLabourHour',
          rules: [],
          disabled: true,
          precision: 2
        },

        {
          type: 'TEXT_AREA',
          label: '工时描述',
          fieldName: 'itemDescribe',
          selfCols: 3,
          maxlength: 300
        },
        {
          type: 'BREAK_SPACE',
          label: '车型列表',
          style: {}
        }
      ];
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          minWidth: '100',
          hidden: this.type === 'show',
          render: (props, h) => {
            return (
              <div>
                <el-button disabled={this.type === 'show'} size="mini" type="text" onClick={() => this.deleRow(props.row, h)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '车系代码',
          dataIndex: 'seriesCode',
          sorter: true
        },
        {
          title: '车系名称',
          dataIndex: 'seriesName',
          sorter: true
        },
        {
          title: '车型代码',
          dataIndex: 'modelCode',
          sorter: true
        },
        {
          title: '车型名称',
          dataIndex: 'modelName',
          sorter: true
        },
        {
          title: '工时数',
          dataIndex: 'stdLabourHour',
          sorter: true,
          editable: true,
          editType: 'number',
          precision: 2,
          defaultEditable: true
        },

        {
          title: '备注',
          dataIndex: 'remark',
          editable: true,
          defaultEditable: true,
          width: 150,
          sorter: true
        }
      ];
    },
    deleRow(row) {
      this.BaseTable.EXECUTE_DELETE([row]);
    },
    addRowClick() {
      this.showChooseModel = true;
    },
    async saveDialog() {
      this.saveData = null;
      const [err, data] = await this.$refs.formPanel.GET_FORM_DATA();
      if (err) return;
      if (data.isAllModel == 10041002) {
        delete data.stdLabourHour; // 防止字段覆盖
      }
      let params = [];
      this.tableData.forEach(x => {
        // 不要用dataSource，可能被编辑了
        params.push({ ...x, ...data });
      });
      params = { ...data, repairItemDTOs: [...params] };
      let res = await saveLabour(this.type, params);
      if (res.resultCode === 200) {
        this.$notify({
          title: '提示信息',
          message: '保存成功！',
          type: 'success'
        });
        this.closeDialog('refresh');
      }
    },
    closeDialog(param) {
      this.$emit('close', false, param);
    },
    closeChooseModelDialog(param) {
      this.showChooseModel = false;
      if (!param || !param.length) return;
      // 判断是否存在重复
      for (let index = 0; index < param.length; index++) {
        const element = param[index];
        let result = this.dataSource.find(item => element.modelCode === item.modelCode);
        if (result) {
          this.$notify.error({ title: '提示信息', message: '添加的数据和已有的车型存在重复' });
          return;
        }
      }
      this.BaseTable.EXECUTE_INSERT(param);
    },
    syncTableFun(val) {
      console.log(val, '更新了。。。');
      this.tableData = val;
    }
  }
};
</script>
